package com.wink_172.library.view

import android.content.Context
import android.text.TextUtils
import android.util.AttributeSet
import android.widget.RelativeLayout
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.GridLayoutManager.SpanSizeLookup
import com.wink_172.library.R
import com.wink_172.library.activity.SmartActivity
import com.wink_172.library.adapter.HomeListAdapter
import com.wink_172.library.callback.ICallback
import com.wink_172.library.model.Constants
import com.wink_172.library.model.BaseDataItem
import com.wink_172.library.model.json.ImageData
import com.wink_172.library.utils.CommonUtils
import java.util.*

/**
 * 选择图片列表控件
 * 请注意
 * 1.需要  android:requestLegacyExternalStorage="true"
 * 2.需要   <provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}" android:exported="false" android:grantUriPermissions="true">
 * <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths"></meta-data>
</provider> *
 * 3.需要动态申请权限
 * 4.provider_paths只需要在library存放一份就可以了，不需要每个项目都放
 */
open class SelectorMultiImage : RelativeLayout {
    open lateinit var listView: CustomRecyclerView
    open lateinit var activity: SmartActivity
    open var callback: ICallback? = null
    open var photoName //只在拍照时候使用
            : String? = null
        set

    constructor(context: Context?) : super(context) {}
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {}
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
    }

    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int
    ) : super(context, attrs, defStyleAttr, defStyleRes) {
    }

    override fun onFinishInflate() {
        super.onFinishInflate()
        initView()
    }

    /**
     * Activity 调用初始化操作
     */
    fun init(activity: SmartActivity, mode: Int, callback: ICallback) {
        this.activity = activity
        this.callback = callback
        val images: List<ImageData> = ArrayList()
        bindImageList(images, true)
    }

    /**
     * swap  交换或者追加
     */
    fun bindImageList(images: List<ImageData>, swap: Boolean) {
        val homeListAdapter = listView!!.adapter as HomeListAdapter?
        val list: MutableList<Any> = ArrayList()
        val orgin_list = homeListAdapter!!.dataList
        for (i in images.indices) {
            val baseDataItem = BaseDataItem(
                (System.currentTimeMillis() / 1000).toInt(),
                Constants.List_Enum.选择图片列表.ordinal
            )
            val imageData = images[i]
            baseDataItem.setObjectData(imageData)
            baseDataItem.callback = mCallBack
            list.add(baseDataItem)
        }
        if (swap) {
            orgin_list?.clear()
            orgin_list?.addAll(list)
        } else {

            orgin_list?.addAll(orgin_list.size - 1, list)
        }
        if (orgin_list!!?.size <= Constants.MAX_PICTURE_NUM9) {
            if (swap) {
                val baseDataItem = BaseDataItem(
                    (System.currentTimeMillis() / 1000).toInt(),
                    Constants.List_Enum.选择图片列表.ordinal
                )
                val imageData = ImageData()
                baseDataItem.setObjectData(imageData)
                baseDataItem.callback = mCallBack
                orgin_list?.add(baseDataItem)
            }
        } else {
            orgin_list?.removeAt(orgin_list.size - 1)
        }
        homeListAdapter.swapContent(orgin_list)
        homeListAdapter.notifyDataSetChanged()

        listView!!.scrollToEnd()//不管上传多少，最右边始终是 上传按钮“+”
    }

    private val mCallBack: HomeListAdapter.BaseViewsHolder.ICallback =
        object : HomeListAdapter.BaseViewsHolder.ICallback {
            override fun postObject(event: Int, vararg args: Any?) {
                when (event) {
                    Constants.EVENT_02 -> {//点击close 按钮
                        val homeListAdapter = listView!!.adapter as HomeListAdapter?
                        val list = homeListAdapter!!.dataList
                        val baseDataItem = args[0] as BaseDataItem
                        list?.remove(baseDataItem)
                        var add_btn = false //当从max_num图片减一
                        var i = 0
                        while (i < list!!?.size) {
                            val item = list[i] as BaseDataItem
                            val imageData = item.data as ImageData
                            if (TextUtils.isEmpty(imageData.local_url) && TextUtils.isEmpty(
                                    imageData.web_url
                                )
                            ) {
                                add_btn = true

                            }
                            i++
                        }
                        if (!add_btn) {
                            val baseDataItem2 = BaseDataItem(-1,Constants.List_Enum.选择图片列表.ordinal)
                            val imageData = ImageData()
                            baseDataItem2.setObjectData(imageData)
                            baseDataItem2.callback = this
                            list.add(baseDataItem2)
                        }
                        homeListAdapter.notifyDataSetChanged()

                        if (callback != null) {
                            callback!!.onSendEvent(Constants.EVENT_05)//
                        }
                    }
                    Constants.EVENT_01 -> {
                        val homeListAdapter = listView!!.adapter as HomeListAdapter?
                        val list = homeListAdapter!!.dataList
                        val baseDataItem = args[0] as BaseDataItem
                        val imageData = baseDataItem.data as ImageData

                        if (TextUtils.isEmpty(imageData.local_url) && TextUtils.isEmpty(imageData.web_url)) {//点击了加号
                            autoSel()

                        } else {//点击图片放大
                            for (i in list!!.indices) {
                                val btem = list.get(i) as BaseDataItem
                                if (btem!!.id == baseDataItem.id) {//点击位置
                                    if (callback != null) {
                                        callback!!.onSendEvent(Constants.EVENT_03,i)//放大图片
                                    }
                                }
                            }


                        }

                    }
                }
            }


        }
    /**
     * 跳转到图库选择
     *      * Manifest.permission.CAMERA
     * Manifest.permission.CAMERA未添加
     *      * Manifest.permission.CAMERA
     * Manifest.permission.CAMERA未添加
     * */
    fun autoSel(){
        if (!activity!!.checkPermissions(Constants.permissions)) {
            callback!!.onSendEvent(Constants.EVENT_01)//选择图片
            activity!!.requestPermissions(
                Constants.ACTIVITY_REQUEST_CODE_PERMISSION,
                Constants.permissions
            )
        } else {
            if (callback != null) {
                callback!!.onSendEvent(Constants.EVENT_01)//选择图片
            }
            photoName = System.currentTimeMillis().toString() + ".jpg"
            CommonUtils.showSelPicDialog(activity, photoName)
        }
    }
    private val TAG = "SelectorMultiImage"
    private fun initView() {
        listView = findViewById(R.id.list_view)
        listView?.init(null, true)
        val gridLayoutManager = GridLayoutManager(context, 3, GridLayoutManager.VERTICAL, false)
        gridLayoutManager.spanSizeLookup = object : SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
//                if (position < 7 || position > 14) {
//                    return 3;
//                }
                return 1
            }
        }
        listView?.setLayoutManager(gridLayoutManager)
    }
}